<template>
  <el-form
    ref="loginForm"
    :model="form"
    :rules="rules"
    label-width="0"
    size="large"
    @keyup.enter="login"
  >
    <el-form-item prop="username">
      <el-input v-model="form.username" clearable placeholder="请输入手机号"> </el-input>
    </el-form-item>
    <el-form-item prop="code" style="margin-bottom: 35px">
      <div class="login-msg-code">
        <el-input v-model="form.code" clearable placeholder="请输入验证码"></el-input>
        <el-button size="mini" @click="getCode" :disabled="showTime"
          >获取验证码<span v-if="showTime"> ({{ time }})</span></el-button
        >
      </div>
    </el-form-item>
    <el-form-item>
      <el-button
        size="mini"
        type="primary"
        style="width: 100%; height: 40px; font-size: 18px"
        :loading="loading"
        @click="handleLogin"
      >
        <span v-if="!loading">立即登录</span>
        <span v-else>登 录 中...</span></el-button
      >
    </el-form-item>
  </el-form>
</template>

<script>
import { validPhone } from '@/utils/validate';
import { phoneIsRegister, sendSmsCode } from '@/api/login';
export default {
  name: 'PhoneForm',
  data() {
    const isPhone = (rule, value, callback) => {
      if (!validPhone(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    };
    return {
      form: {
        username: '',
        code: '',
        loginType: 1, // 短信验证
      },
      loading: false,
      rules: {
        username: [
          { required: true, message: '请输入手机号' },
          { required: true, validator: isPhone, trigger: 'blur' },
        ],
        code: [{ required: true, message: '请输入验证码' }],
      },
      showTime: false,
      time: 0,
      islogin: false,
    };
  },
  mounted() {},
  methods: {
    // getcode方法用于获取验证码并进行相关的逻辑处理
    getCode() {
      // 调用validateField方法对名为username的字段进行校验，并将校验结果通过回调函数的参数usernameError传递给回调函数
      this.$refs['loginForm'].validateField('username', async (usernameError) => {
        // 校验通过，则执行以下操作：
        if (!usernameError) {
          let query = {
            phone: this.form.username,
          };
          // 设置showTime属性为true，用于控制显示倒计时
          this.showTime = true;
          this.time = 60;
          let t = setInterval(() => {
            this.time -= 1;
            if (this.time < 1) {
              clearInterval(t);
              this.showTime = false;
              this.time = 0;
            }
          }, 1000);

          const res = await phoneIsRegister(query);
          if (res.code != 200) {
            this.$message.error(res.message || res.msg);
          } else {
            sendSmsCode(query)
              .then((res) => {})
              .catch((err) => {
                this.$message.error('获取验证码失败！');
              });
          }
        }
      });
    },
    handleLogin() {
      this.$refs['loginForm'].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch('Login', this.form)
            .then(() => {
              this.$router.push({ path: '/' }).catch(() => {});
            })
            .catch(() => {
              this.loading = false;
            });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.login-msg-code {
  display: flex;
  width: 100%;
}

.login-msg-code .el-button {
  margin-left: 10px;
  --el-button-size: 42px;
}
</style>
